package server;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import common.Constants;

public class SocketManager {
	private DatagramSocket socket;
	private byte[] buffer;
	private static SocketManager current;
	
	public SocketManager() throws SocketException {
		this.socket = new DatagramSocket(Constants.SERVER_PORT);
		this.buffer = new byte[Constants.BUFFER_LENGTH];
	}

	public DatagramSocket getSocket() {
		return socket;
	}

	public void setSocket(DatagramSocket socket) {
		this.socket = socket;
	}

	public byte[] getBuffer() {
		return buffer;
	}

	public void setBuffer(byte[] buffer) {
		this.buffer = buffer;
	}

	public DatagramPacket GetPacket() throws IOException {
		DatagramPacket requestPacket = new DatagramPacket(this.buffer,
				this.buffer.length);
		this.socket.receive(requestPacket);
		return requestPacket;
	}

	public void SendPacket(DatagramPacket replyPacket) throws IOException {
		if (socket != null){
			if (replyPacket != null){
				socket.send(replyPacket);	
			}
		}
		else {
			System.out.println("socket closed already");
		}
	}
	
	public void CloseSocket() {
		if (this.socket != null) {
			this.socket.close();
			System.out.println("Close server socket");
		}
	}
	public static SocketManager getCurrent() throws SocketException{
		if (current == null){
			current = new SocketManager();
		}
		return current;
	}
}
